package com.charges.service.impl;

import com.charges.constant.ErrorCode;
import com.charges.vo.RestResult;
import com.charges.entity.RechargeTransactionDO;
import com.charges.entity.RedemptionCodeDO;
import com.charges.exception.BusinessErrorEnum;
import com.charges.query.RedemptionCodeQuery;
import com.charges.repository.RechargeTransactionRepository;
import com.charges.repository.RedemptionCodeRepository;
import com.charges.service.RedemptionCodeService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * 核销码服务实现类
 * @author admin
 */
@Service
public class RedemptionCodeServiceImpl implements RedemptionCodeService {

    @Autowired
    private RedemptionCodeRepository redemptionCodeRepository;

    @Autowired
    private RechargeTransactionRepository rechargeTransactionRepository;

    /**
     * 验证核销码有效性
     * @param redemptionCode 核销码
     * @return 核销码验证结果
     */
    @Override
    public RestResult validateRedemptionCode(String redemptionCode) {
        RedemptionCodeDO codeDO = redemptionCodeRepository.findByCode(redemptionCode);
        if (codeDO == null) {
            return RestResult.fail(ErrorCode.CODE_NOT_FOUND, "核销码不存在");
        }
        if (!"active".equals(codeDO.getStatus())) {
            return RestResult.fail(ErrorCode.CODE_INVALID, "核销码已使用或已过期");
        }
        return RestResult.success("核销码有效");
    }

    /**
     * 进行权益充值
     * @param redemptionCode 核销码
     * @return 充值结果
     */
    @Override
    @Transactional
    public RestResult rechargeWithRedemptionCode(String redemptionCode) {
        try {
            RedemptionCodeDO codeDO = redemptionCodeRepository.findByCode(redemptionCode);
            if (codeDO == null) {
                return RestResult.fail(ErrorCode.CODE_NOT_FOUND, "核销码不存在");
            }
            if (!"active".equals(codeDO.getStatus())) {
                return RestResult.fail(ErrorCode.CODE_INVALID, "核销码已使用或已过期");
            }

            // 更新核销码状态为used
            codeDO.setStatus(RedemptionCodeDO.Status.used);
            codeDO.setUpdateTime(LocalDateTime.now());
            redemptionCodeRepository.save(codeDO);

            // 获取核销码关联的充值金额
            BigDecimal rechargeAmount = codeDO.getRechargeAmount();

            // 根据核销码关联的权益名称，更新权益管理表中的权益状态为unavailable
            // TODO: 实现权益管理表的更新逻辑

            // 在充值交易记录表中插入一条成功记录
            RechargeTransactionDO transactionDO = new RechargeTransactionDO();
            transactionDO.setCode(redemptionCode);
            transactionDO.setAmount(rechargeAmount);
            transactionDO.setStatus("success");
            transactionDO.setCreateTime(LocalDateTime.now());
            rechargeTransactionRepository.save(transactionDO);

            return RestResult.success("充值成功");
        } catch (Exception e) {
            // FIXME: 记录异常日志
            return RestResult.fail(ErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 根据查询条件获取核销码对应的充值金额
     * @param query 查询条件
     * @return 充值金额结果
     */
    @Override
    public RestResult<Double> getRechargeAmountByRedemptionCode(RedemptionCodeQuery query) {
        String redemptionCode = query.getRedemptionCode();
        Optional<RedemptionCodeDO> optionalRedemptionCode = Optional.of(redemptionCodeRepository.findByCode(redemptionCode));

        if (!optionalRedemptionCode.isPresent()) {
            return RestResult.fail(BusinessErrorEnum.BUSINESS_ERROR.getCode(), "核销码不存在");
        }

        RedemptionCodeDO redemptionCodeDO = optionalRedemptionCode.get();
        if (redemptionCodeDO.getStatus() == RedemptionCodeDO.Status.used || redemptionCodeDO.getStatus() == RedemptionCodeDO.Status.expired) {
            return RestResult.fail(BusinessErrorEnum.BUSINESS_ERROR.getCode(), "核销码已使用或已过期");
        }

        return RestResult.success(redemptionCodeDO.getRechargeAmount().doubleValue());
    }
}